package web.get;

import com.fasterxml.jackson.databind.ObjectMapper;
import domain.Book;
import domain.User;
import service.BookService;
import service.UserService;
import service.impl.BookServiceImpl;
import service.impl.UserServiceImpl;
import util.ServletUtil;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/getCollect")
public class GetCollectServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        Map<String,Object> msg = new HashMap<>();
        List<Book> bookList = new ArrayList<>();
        int uid = ServletUtil.checkLogin(request).getUid();
        UserService us = new UserServiceImpl();
        BookService bs = new BookServiceImpl();
        List<Integer> collect = us.getCollect(new User().setUid(uid));
        //遍历collect列表获取书籍信息
        for(int bid:collect){
            Book book = bs.getBookbybid(bid);
            if(book!=null){
                bookList.add(bs.getBookbybid(bid));

            }
        }
        msg.put("collect",bookList);
        new ObjectMapper().writeValue(response.getOutputStream(),msg);
    }
}
